#include "WinHelper.h"
#include <windowsx.h>
#include <commctrl.h>
using namespace std;

void CenterToScreen(int width, int height, int &x, int &y)
{
	int sx = GetSystemMetrics(SM_CXSCREEN);
	int sy = GetSystemMetrics(SM_CYSCREEN);

    int cx = sx/2;
    int cy = sy/2;

    x = cx - width/2;
    y = cy - height/2;
}

void SetDefaultFont(HWND hWnd)
{
	HFONT font = (HFONT) GetStockObject(DEFAULT_GUI_FONT);
	SendMessageW(hWnd, WM_SETFONT, (LPARAM) (void *) font, TRUE);
}

bool OpenLink(LPARAM lParam)
{
	PNMLINK link_by_lparam = (PNMLINK) lParam;
	if (!link_by_lparam)
		return false;
	LITEM   item    = link_by_lparam->item;
	if (item.iLink != 0)
		return false;
	ShellExecuteW(NULL, L"open", item.szUrl, NULL, NULL, SW_SHOW);
	return true;
}

void WindowToScreenCenter(HWND hWnd, bool show)
{
	int w, h, x, y;
    RECT rect;
    GetWindowRect(hWnd, &rect);
    w = rect.right - rect.left;
    h = rect.bottom - rect.top;
    CenterToScreen(w, h, x, y);
    SetWindowPos(hWnd, (show ? HWND_TOP : NULL),
				x, y, 0, 0, SWP_NOSIZE | (show ? SWP_SHOWWINDOW : 0));
}

bool SetFontSize(HWND hWnd, size_t s)
{
	HFONT font = NULL;
    font = (HFONT) SendMessageW(hWnd, WM_GETFONT, 0, 0);
    if (!font)
        font = (HFONT) GetStockObject(DEFAULT_GUI_FONT);
	HDC hdc = GetWindowDC(hWnd);
    LOGFONTW lf;
	ZeroMemory(&lf, sizeof(lf));
    GetTextFaceW(hdc, 32, lf.lfFaceName);
	lf.lfHeight = s;
    font = CreateFontIndirectW(&lf);
    if (!font)
		return false;
    SendMessageW(hWnd, WM_SETFONT, (WPARAM) (void *) font, TRUE);
    ReleaseDC(hWnd, hdc);
    return true;
}

wstring GetStringW(HWND hWnd)
{
	size_t s = GetWindowTextLengthW(hWnd);
	wchar_t *temp = new wchar_t[s + 1];
	GetWindowTextW(hWnd, temp, s + 1);
	wstring str = temp;
	delete [] temp;
	return str;
}

string GetStringA(HWND hWnd)
{
	size_t s = GetWindowTextLengthW(hWnd);
	char *temp = new char[s + 1];
	GetWindowTextA(hWnd, temp, s + 1);
	string str = temp;
	delete [] temp;
	return str;
}
